package com.dys.test06;

import java.io.*;
import java.net.Socket;

/**
 * @className: com.dys.test06.ServerThread
 * @description: 服务器必须一直在监听 ，一直开着，等待客户端的请求
 * @author: pine cone
 * @version: v1.0.0
 * @createTime: 2024/08/21 下午10:13
 */
public class ServerThread extends Thread {

    InputStream is = null;
    ObjectInputStream ois = null;
    OutputStream os = null;
    DataOutputStream dos = null;
    Socket s = null;

    public ServerThread(Socket s) {
        this.s = s;
    }

    @Override
    public void run() {
        try {
            // 3.等着客户端发来的信息：
            is = s.getInputStream();
            ois = new ObjectInputStream(is);

            // 4.读取客户端发送过来的数据
            User user = (User) (ois.readObject());
            boolean flag = false;

            // 对账号和密码进行验证
            if (user.getUsername().equals("张淑娜") && user.getPassword().equals("123")) {
                flag = true;
            }

            // 向客户端输出结果：---》操作流---》输出流
            os = s.getOutputStream();
            dos = new DataOutputStream(os);
            dos.writeBoolean(flag);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            // 4.关流+关闭网络资源
            try {
                if (dos != null) {
                    dos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (ois != null) {
                    ois.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
